
<template>
  <div>

    <div v-show="!isprint && !$root.$data.cloth_print.show">
      <!--导航-->
      <div  class="headerNav not-print">
        <div>
          <h1 v-if="$root.$data.is_szy" class="side-left">
            <a href="/" style="color: #fff; text-decoration: none" >
                <img :src="'/static/logo/'+logo_name"  class="logo" />
                <img src="/static/logo/logo_yjt.png" class="logo logo-ekt" />
                <span class="vm">快捷下单助手</span>
            </a>
          </h1>

          <h1 class="side-left" v-else>
            <a href="/"  style="color: #fff; text-decoration: none"   v-if="logos[$root.$data.cid] && logos[$root.$data.cid].src" >
              <img  :src="logos[$root.$data.cid].src" :class="['logo', logos[$root.$data.cid].classn]" />
              <span class="vm">快捷下单助手</span>
            </a>
            <a href="/" style="color: #fff; text-decoration: none" v-else>
            {{
                $root.$data.cid == 15 || $root.$data.cid == 33
                ? "后勤综合服务受理系统"
                : `${cname}下单助手`
            }}</a>
          </h1>

          <ul class="side-left side-nav-bar">
            <template v-if="$root.$data.is_szy">
              <li :class="{ curr: getComputedView.waste }" @click="navClickFn(15)">
                医废确认
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.waste" class="curr-img">
              </li>
              <li
                  :class="[{ curr: getComputedView.set }]"
                  @click="navClickFn(6)"
              >
                医废指南
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.set" class="curr-img"> 
              </li>
            </template>

            <template v-else>
              <li v-if="$root.$data.cid == '15'" :class="{ curr: getComputedView.ssxd }" @click="navClickFn(1)">
                输送下单
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.ssxd" class="curr-img">
              </li>
              <li
                v-if="['15','33','21'].includes($root.$data.cid) "
                :class="{ curr: currView == 'view_10' }"
                @click="navClickFn(10)"
              >
                {{currMtTitle}}
                <img src="../assets/img//nav-curr.png" alt="" v-if="currView == 'view_10'" class="curr-img">
              </li>
              <li v-if="$root.$data.cid != '15'" :class="{ curr: getComputedView.ssxd }" @click="navClickFn(1)">
                输送下单
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.ssxd" class="curr-img">
              </li>
              <li :class="{ curr: getComputedView.waste }" @click="navClickFn(15)">
                医废确认
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.waste" class="curr-img">
              </li>
              <li v-if="isOpenCloth" :class="{ curr: currView == 'view_8' }" @click="navClickFn(8)">
                医用织物
                <img src="../assets/img//nav-curr.png" alt="" v-if="currView == 'view_8'" class="curr-img">
              </li>
              <li :class="{ curr: getComputedView.look }" @click="navClickFn(3)">
                查看
                <img src="../assets/img//nav-curr.png" alt="" v-if="getComputedView.look" class="curr-img">
              </li>
              <li
                :class="['nav-has-sub',{ curr: getComputedView.set }]"
                @click="navClickFn(4)"
              >
                设置
                <div class="service-menu">
                  <ul class="menu-list">
                    <li
                      class="menu-item"
                      :class="{ curr: currView == 'view_4' }"
                      @click.stop="navClickFn(4)"
                    >起点设置</li>
                    <li class="menu-item" @click.stop="navClickFn(6)">下单指南</li>
                    <li
                        class="menu-item"
                        @click.stop="troubleShootingClickFn()"
                        v-if="isSixthHospital"
                    >故障排除</li>
                  </ul>
                </div>
                <img src="../assets/img//nav-curr.png" alt="" v-if="currView == 'view_6' || currView == 'view_4' || currView == 'view_14'" class="curr-img">
              </li>
            </template>
          </ul>

          <div class="user-class">
            <p :title="uname">{{ uname }}</p>
            <img src="../assets/img//logout.png" alt="" class="logout-icon">
            <a href="/logout" >[ 注销 ]</a>
          </div>
        </div>
      </div>

      <troubleShootingBox
          v-show="troubleShootingBoxShow && isSixthHospital"
          @closeTroubleShootingBox="closeTroubleShootingBox"
      ></troubleShootingBox>

      <!--内容区-->
      <div class="mainCon">
        <!--默认起点-->
        <component
          is="navbar"
          :startAddress="startAddress"
          :isOpenCloth="isOpenCloth"
          :currView="currView"
          v-if="(!$root.$data.is_szy && showCurrViewFlag && currView != 'view_8') || ($root.$data.is_szy && currView != 'view_6')"
          @updateView="navClickFn"
          @updateLisNavTab="updateLisNavTab"
          @updateTroubleShooting="troubleShootingClickFn"
        ></component>

        <div class="mainCon-box">
          <component
            v-if="isCurrViewFlag"
            :is="currView"
            @startSetOk="startSet"
            :start="startAddress"
            :room-lis="roomLis"
            :repeat-id="repeatId"
            @goToSetRepeat="goToRepeat"
            :hisks="hisKs"
            :today-time="todayTime"
            :site-alias="siteAlias"
            :need-set-bad="needSetBad"
            @sendsocket="socketSend"
            @handletabsetbad="needSetBadStatus"
            :lisNavTabKey="lisNavTabKey"
          >
          </component>
        </div>
      </div>

      <div class="qrcode-bg not-print" v-if="isShowQR" @click="hidePop"></div>
      <div class="qrcode-pop not-print" v-if="isShowQR">
        <div class="qrcode-main">
          <img src="../assets/img//qrcode.jpg" alt="" />
          <div class="qrcode-text">
            <h2>关注公众号获得更多后勤服务</h2>
            <template v-if="phoneData.length > 0">
              <p>{{ cname }}调度中心服务热线</p>
              <ul>
                <li v-for="(item, index) in phoneData" :key="index">
                  {{ item.main }} ({{ item.short }})
                </li>
              </ul>
            </template>
          </div>
        </div>
      </div>

      <template v-if="!$root.$data.is_szy">
        <start-tips v-if="setStartAddress" v-on:goto="goToStartFn"> </start-tips>
        <off-duty v-if="offDutyPop" @close="closeOffDutyPop"> </off-duty>
        <TkboyTips
          :start-add="startAdd"
          :tips-lis="tipsLis"
          :orders="orders"
          :notices="notices"
        ></TkboyTips>
      </template> 

      
    </div>

    <print-box
      v-if="isprint"
      :print-lis="printLis"
      :start="startAddress"
      @isprintfn="isPrintFn"
    >
    </print-box>
    <orderPrint
      v-if="$root.$data.cloth_print.show"
    ></orderPrint>
  </div>
</template>
<script>
  import startTips from "../components/startTips.vue";
  import maintain from "../components/order-maintain.vue";
  import order from "../components/order.vue";
  import faster from "../components/faster.vue";
  import lis from "../components/lis.vue";
  import his from "../components/his.vue";
  import guide from "../components/guide.vue";
  import clothOrder from '../components/clothing/clothOrder'
  // import clothSetting from '../components/clothing/clothingSettings'
  import start from "../components/startAddress.vue";
  import offDutys from "../tips/offDutyTips.vue";
  import today from "../common/today";
  import printBox from "../components/lis-print.vue";
  import orderPrint from '../components/clothing/sub/order-print.vue'
  import TkboyTips from '../tips/tkboy-tips.vue'
  import troubleShootingBox from "../tips/troubleShootingBox.vue";
  import navbar from "../components/nav-bar.vue";

  import {
    getPhoneUrl,
    siteOriginUrl,
    printUrl,
    wasteNumberUrl,
    getWasteCategoryUrl,
  } from "../common/ajax";
  import {
      logoutAxios,
      clothKsAxios,clothInfoAxios,getMyPswStatu
  } from '../server/getData'
  import ClassifyModal from "../components/waste/classify-modal.vue";
  import MonthModal from "../components/waste/month-modal.vue";
  import DetailModal from "../components/waste/detail-modal.vue";
  import QualityModal from "../components/waste/quality-modal.vue";
  import GraphModal from "../components/waste/graph-modal.vue";
  import WasteLabel from "../components/waste/label.vue";
  import { mapActions } from 'vuex';

export default {
  name: "layout",
  components: {
    "start-tips": startTips,
    view_1: order,
    view_2: faster,
    view_3: lis,
    view_4: start,
    view_5: his,
    view_6: guide,
    view_8: clothOrder,
    // view_14: clothSetting,
    view_15: ClassifyModal,
    view_16: MonthModal,
    view_17: DetailModal,
    view_18: QualityModal,
    view_19: GraphModal,
    view_20: WasteLabel,
    navbar,
    "off-duty": offDutys,
    "print-box": printBox,
      orderPrint,
    view_10: maintain,
    TkboyTips,
    troubleShootingBox,
  },
  data() {
    return {
      logo_name: "",

      isprint: false,
      isCurrViewFlag:true,
      printLis: [],
      
      setStartAddress: false, //是否需要设置默认起点,true-需要设置，false-不需要
      startAddress: "", //起点地址
      startAdd: { ld: "", lc: "", ks: "" },
      roomLis: [], //
      cname: Cookies.get("categoryname"),
      uname: Cookies.get("nickname"),
      //socket信息
      tipsLis: {
        show: false,
        lis: [],
      },
      conn: Object(),
      needSetBad: true,
      //时间
      todayTime: today.init("YY-MM-DD"),
      //导航
      currView: "",
      repeatId: "",
      offDutyPop: false,
      hisKs: "",
      // 二级导航
      showCurrViewFlag:true,
      // 存储在localStorage中的订单信息

      orders: {
        time: "", //时间，所存储的信息的时间-年-月-日
        lis: [
          //未‘已知悉’的信息列表，具体的情况等确定后修改
          // {
          //   istobg:false, //是否开启到bg；由于拒单到bg的也是需要提示的
          //   uid:'', //发单人id？ 人名 // 用cookie的人名进行过滤
          //   type:'', //订单类别：输送（1），维修（2）
          //   otype:'', //订单状态，字符串，文字
          //   sn:'', //订单sn
          //   id:'1', //订单ID
          //   classify:'', //订单类型,大类
          //   catalog:'', //订单类别，小类
          //   site:'', //订单地址（输送的起点，维修的位置）
          //   createdtime:'', //下单时间
          //   changetime:'', //状态改变时间
          //   operator:'aaa' //操作人,人员名称
          // }
        ],
      },
      siteAlias: [],
      isShowQR: false,
      phoneData: [
        // {
        //     main: '12345678',
        //     short: '1234'
        // },
        // {
        //     main: '6789000',
        //     short: '6789'
        // }
      ],
      // isShowModal: false,

      notices: null, 

      wasteNum: 0,
      logos: {
        11: { src: "/static/cdn/sfy_bs.png", classn: "" },
        12: { src: "/static/cdn/sfy_bs.png", classn: "" },
        17: { src: "/static/cdn/zsly_bs.png", classn: "" }, // 中山六院
        19: { src: "/static/cdn/zszl_bs.png", classn: "min" }, // 中山肿瘤
        101: {src:"https://say.ektlang.com/static/logo/nb1.png",class:""}
      },
      troubleShootingBoxShow: false,
      isSixthHospital: ['17','19','57'].includes(Cookies.get("categoryid")),//Cookies.get("categoryid") == 17 || Cookies.get("categoryid") == 19 || Cookies.get("categoryid") == 57,
      lisNavTabKey:'trans', // 查看栏的二级导航
      isOpenCloth:false, // 是否开通被服功能
      currMtTitle: Cookies.get('categoryid') != '33' ? '维修下单' : '服务受理'
    };
  },
  
  computed:{
    getComputedView(){
      // 
      return {
        ssxd: ['view_1', 'view_2', 'view_5'].includes(this.currView),
        waste: ['view_15', 'view_16', 'view_17', 'view_18', 'view_19',"view_20"].includes(this.currView),
        look: ['view_3', 'view_12', 'view_13'].includes(this.currView),
        set: ['view_6', 'view_4', 'view_14'].includes(this.currView),
        
      }
    }
  },
  watch:{
    'startAddress':function(oldVal,Val){
      const that = this
      that.startAddress =  oldVal
      that.isCurrViewFlag = false
      that.$nextTick(function(){
        that.isCurrViewFlag = true
      })
    }
  },
  created() {

    if(this.$root.$data.is_szy){
      this.logo_name = process.env.ENV_LOGO
      getMyPswStatu().then(res=>{
        if(res.success && res.data != 1){
          console.log("可以正常使用");
        }else {
          window.location.assign("/")
        }
      },()=>{window.location.assign("/")})
    }
    this.currView = this.currV()
    this.$root.$data.cid = Cookies.get("categoryid");
    this.needSetBadStatus("get", "");
    this.getWasteCategory();
    this.getWasteConfig()
    if(this.$root.$data.is_szy){
      return
    }
    // 检测账号是否开通被服功能
    this.checkAccountOpenCloth()
    if (this.$root.$data.cid == 28) {
      this.siteAlias = ksAlias;
    }
    this.loadStartAddress();
    this.isPrintFn("", {});
    
    if (window["WebSocket"]) {
      var url = ""
      if(process.env.NODE_ENV == 'development'){
        url = 'ws://say.ektlang.com:9139/ws?cat='
        //url =  "ws://192.168.2.17:9139/ws?cat=";
      }else {
        var hostname = window.location.hostname;
        var port = this.$root.$data.cid == 19 ? 8082 : 9139; // 中山肿瘤时端口改为8082
        url = "://" + hostname + ":" + port + "/ws?cat=";
        let pr = window.location.protocol;
        if (pr == "https:") {
          url = "wss://mfs.eai9.com/ws?cat=";
        } else {
          url = "ws" + url;
        }
      }
      this.conn = new WebSocket(url + this.$root.$data.cid);
      this.conn.onclose = function (evt) {};
      this.conn.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        let name = Cookies.get("nickname");
        //订单信息
        if (data.uid == name) {
          if (localStorage.changedOrders) {
            var localOrders = JSON.parse(localStorage.getItem("changedOrders"));
            var localTime = localOrders.time;
            var serverTime = this.getServerTime();
            if (serverTime == localTime) {
              this.orders.lis.unshift(data);
              localStorage.setItem(
                "changedOrders",
                JSON.stringify(this.orders)
              );
            } else {
              this.resetLocal(data);
            }
          } else {
            this.resetLocal(data);
          }
        }
        if (data.type == 3) {
          //下班主动刷新
          location.reload(true);
          this.tipsLis.show = true;
          this.tipsLis.lis = [];
        } else if (data.type == 4) {
          //上班
          this.tipsLis.show = true;
          this.tipsLis.lis = [];
        } else if (data.type == 10) {
          this.notices  = data
          //快捷公告
        }
      }.bind(this);
    }
    if (localStorage.changedOrders) {
      let co = JSON.parse(localStorage.getItem("changedOrders"));
      let td = today.init("YY-MM-DD").replace(/-/g, "");
      if (co.time == td) {
        this.orders = co;
      } else {
        this.orders.time = td;
        localStorage.setItem("changedOrders", JSON.stringify(this.orders));
      }
    }


  },
  methods: {
    currV() {
      if(this.$root.$data.is_szy){
        return "view_15"
      }
      let v = sessionStorage.getItem("ektFastCurrView");
      let id = Cookies.get("categoryid");
      if (v == null || v == "") {
        if (id == "33") {
          return "view_10";
        } else {
          return "view_1";
        }
      } else {
        if (id == "33") {
          return "view_10";
        } else if (
          (id != "17" && v == "view_5") ||
          (id != "33" && v == "view_10")
        ) {
          return "view_1";
        } else {
          return v;
        }
      }
    },
    checkAccountOpenCloth(){ // 检测账号是否开通被服
        /*2021.05 2.0版本
       根据账号 有无绑定科室，绑定科室是否有开启
       若 无绑定 || 绑定科室全关闭  没有申领入口
       则 有申领入口
        * */
        this.isOpenCloth = false
        clothKsAxios().then(res=>{
            if(res.data.length > 0){
              let ks = ""
              res.data.forEach(v=>{
                if(v.isbool == 0){
                  ks = v.addr
                  this.isOpenCloth = true
                }
              })
              if(this.isOpenCloth){
                clothInfoAxios(ks).then(res=>{
                  this.$root.$data.cloth_des = res.data && res.data.weaving_show_des == "1"
                })
              }
            }
            this.showCurrViewFlag = true
        },res=>{})
    },
    updateLisNavTab(key){ // 更新查看栏二级导航栏显示隐藏
      this.lisNavTabKey = key
    },
    closeTroubleShootingBox(value) {
      this.troubleShootingBoxShow = value;
    },
    getWasteNumber() {
      jQuery.ajax({
        url: wasteNumberUrl,
        type: "get",
        cache: false,
        success: function (data) {
          if (data.success) {
            this.wasteNum = data.data.total;
          }
        }.bind(this),
      });
    },
    getPhoneData() {
      jQuery.ajax({
        url: getPhoneUrl,
        type: "post",
        dataType: "json",
        data: {},
        cache: false,
        success: function (data) {
          if (data.success) {
            this.phoneData = data.data;
          } else {
            throwErrorTips("获取失败", data.msg);
          }
        }.bind(this),
        error: function (xhr, status) {
          throwErrorTips("获取失败", status);
        }.bind(this),
      });
    },
    showPop() {
      this.isShowQR = true;
      this.getPhoneData();
    },
    hidePop() {
      this.isShowQR = false;
    },
    loadStartAddress() {
      this.roomLis = [];
      jQuery.ajax({
        url: siteOriginUrl,
        type: "GET",
        dataType: "json",
        cache: false,
        success: function (data) {
          if (data.success) {
            let d = data.data;
            if (typeof d.ld != "undefined") {
              this.startAddress = d.ld + " " + d.lc + " " + d.ks;
              let r = d.ks.split(" / ");
              let rls = [];

              for (var room of r) {
                this.roomLis.push({ name: room });
                let ind = -1;

                this.siteAlias.forEach(function (vaule, index) {
                  if (vaule.alias === room) {
                    ind = index;
                  }
                });
                if (ind == -1) {
                  rls.push(room);
                } else {
                  for (var val of this.siteAlias[ind].room) {
                    rls.push(val.name);
                  }
                }
              }
              this.hisKs = rls.join(",");
              this.startAdd = {
                ld: d.ld,
                lc: d.lc,
                ks: jQuery.trim(rls.join(" / ")),
              };
              this.setStartAddress = false;
              d.state == 1
                ? ((this.$root.$data.ssOffDuty = true),
                  (this.offDutyPop = true))
                : ((this.$root.$data.ssOffDuty = false),
                  (this.offDutyPop = false));
            } else {
              this.startAddress = "";
              this.setStartAddress = true;
            }
          } else {
            throwErrorTips("获取默认起点信息失败", data.msg);
          }
        }.bind(this),
      });
    },
    closeOffDutyPop() {
      this.offDutyPop = false;
    },
    navClickFn(index) {
      console.log(index);
      const that = this
      if (that.setStartAddress == false) {
        that.currView = "view_" + index;
        sessionStorage.setItem("ektFastCurrView", that.currView);
      }
      that.showCurrViewFlag = false
      that.$nextTick(function(){
        that.showCurrViewFlag = true
      })
    },
    goToStartFn() {
      // this.currView = "view_4";
      this.setStartAddress = false;
      this.navClickFn(4)
    },
    troubleShootingClickFn() {
      this.troubleShootingBoxShow = true;
    },
    startSet() {
      if (this.$root.$data.cid == 15 || this.$root.$data.cid == 33) {
        // this.currView = "view_10";
        this.navClickFn(10)
      } else {
        this.navClickFn(1)
        // this.currView = "view_1";
      }
      this.loadStartAddress();
    },
    goToRepeat() {
      this.currView = "view_1";
    },
    getServerTime() {
      var serverDate = new Date(
        jQuery.ajax({ async: false }).getResponseHeader("Date")
      );
      var serverTime =
        String(serverDate.getFullYear()) +
        String(serverDate.getMonth()) +
        String(serverDate.getDate());
      return serverTime;
    },
    resetLocal(data) {
      this.orders.time = this.getServerTime();
      this.orders.lis = [];
      this.orders.lis.unshift(data);
      localStorage.setItem("changedOrders", JSON.stringify(this.orders));
    },
    //
    socketSend(str) {
      this.conn.send(str);
    },
    
    //退出
    logout() {
        logoutAxios().then(res=>{
            setTimeout(function () {
                window.location.href = "/";
            }, 200);
        },res=>{})
    },
    //打印
    isPrintFn(postjson, localp) {
      let p = localStorage.getItem("-ektprint-");
      localp["cid"] = this.$root.$data.cid;
      if (p != null && p != "") {
        let localprint = JSON.parse(p);
        for (var i = 0; i < localprint.length; i++) {
          let val = localprint[i];
          if (val.cid == this.$root.$data.cid) {
            let posts = { ids: val.ids, ctime: val.ctime };
            this.printAjax(JSON.stringify(posts), val, 1);
          }
        }
        this.printAjax(postjson, localp, 2);
      } else {
        this.printAjax(postjson, localp, 0);
      }
    },
    printAjax(postjson, olocalobj, type) {
      if (postjson != "") {
        let l = [];
        let ls = localStorage.getItem("-ektprint-");
        if (ls != null && ls != "") {
          l = JSON.parse(ls);
        }
        jQuery.ajax({
          url: printUrl,
          type: "post",
          dataType: "json",
          data: postjson,
          cache: false,
          success: function (data) {
            if (data.success) {
              if (type == 1) {
                //需要清空，再存
                let nl = [];
                let ps = JSON.parse(postjson);
                for (var val of l) {
                  if (val.only != olocalobj.only) {
                    nl.push(val);
                  }
                }
                localStorage.setItem("-ektprint-", JSON.stringify(nl));
              }
            } else {
              if (type != 1) {
                l.push(olocalobj);
                localStorage.setItem("-ektprint-", JSON.stringify(l));
              }
            }
          }.bind(this),
          error: function (xhr) {
            if (type != 1) {
              l.push(olocalobj);
              localStorage.setItem("-ektprint-", JSON.stringify(l));
            }
          }.bind(this),
        });
      }
    },
    needSetBadStatus(opt, status) {
      if (this.$root.$data.cid == 17 && opt == "get") {
        this.needSetBad = true;
        return;
      }
      let arr = JSON.parse(
          decodeURI(localStorage.getItem("ektNeedSetBadStatus"))
        ),
        self = this;
      if (arr) {
        if (arr.length > 0) {
          let ind = -1;
          arr.forEach(function (val, index) {
            if (self.uname == val.uname) {
              ind = index;
              return;
            }
          });
          if (ind == -1) {
            opt == "get"
              ? (this.needSetBad = true)
              : ((this.needSetBad = status),
                arr.push({ uname: this.uname, status: status }),
                localStorage.setItem(
                  "ektNeedSetBadStatus",
                  encodeURI(JSON.stringify(arr))
                ));
          } else {
            opt == "get"
              ? (this.needSetBad = arr[ind].status)
              : ((this.needSetBad = status),
                (arr[ind].status = status),
                localStorage.setItem(
                  "ektNeedSetBadStatus",
                  encodeURI(JSON.stringify(arr))
                ));
          }
        } else {
          opt == "get"
            ? (this.needSetBad = true)
            : ((this.needSetBad = status),
              (arr = [{ uname: this.uname, status: status }]),
              localStorage.setItem(
                "ektNeedSetBadStatus",
                encodeURI(JSON.stringify(arr))
              ));
        }
      } else {
        opt == "get"
          ? (this.needSetBad = true)
          : ((this.needSetBad = status),
            (arr = [{ uname: this.uname, status: status }]),
            localStorage.setItem(
              "ektNeedSetBadStatus",
              encodeURI(JSON.stringify(arr))
            ));
      }
    },

    getWasteCategory() {
      jQuery.ajax({
        url: getWasteCategoryUrl,
        type: "post",
        data: JSON.stringify({
          sday: this.todayTime,
          eday: this.todayTime,
          stime: "00:00",
          etime: "23:59",
        }),
        success: function (data) {
          if (data.success) {
            this.getWasteNumber();
          }
        }.bind(this),
        error: function (err) {}.bind(this),
      });
    },
    ...mapActions(["getWasteConfig"])
  },
  
};
</script>
<style lang="less">
    @import "../assets/less/head.less";
    @import "../assets/less/waste.less";
</style>